let domain = require('./domain')
const jsonBigint = require('json-bigint')

let cheche_request = {}
let timer = null

function base(url, method, data = {}, header = {'Content-Type': 'application/x-www-form-urlencoded'}) {
	url = domain.url + url
	// 配置防抖
	const cheche_request_key = `${ method }_${ url }`
	if (cheche_request[cheche_request_key]) {
		cheche_request[cheche_request_key].abort()
	}
	return new Promise((resolve, reject) => {
		let reqData = data
		cheche_request[cheche_request_key] = wx.request({
			url,
			data,
			method,
			dataType: 'other',
			header: {
				token: domain.token,
				...header, // 默认值
			},
			success({ data }) {
        data = jsonBigint.parse(data)
        console.log(url,"url");
				if (data.code === 1010 && !(url.includes("/smell/record/unmakeList"))) {
					for(let key in cheche_request) {
						cheche_request[key].abort()
					}
					wx.showToast({
						title: '登陆已过期',
						icon: 'none',
						duration: 2000,
						mask: true,
						success: () => {
              if(timer){

                timer&&clearTimeout(timer)
              }
              timer = setTimeout(() => wx.navigateTo({ url: '/pages/login/index' }), 2000)
						},
					})
					reject()
				} else {
					resolve(data)
				} /*else if (data.code === 0) {
					resolve(data)
				} else {
					wx.showToast({
						title: data.tip,
						icon: 'none',
						duration: 2500,
					})
					reject()
				}*/
			},
			fail(err) {
				console.log(err)
				reject(err)
			},
			complete: () => {
				delete cheche_request[cheche_request_key]
			}
		})
	})
}
module.exports = {
	get(route, data) {
		return base(route, 'GET', data)
	},
	post(route, data) {
		return base(route, 'POST', data)
	},
	postJSON(route, data) {
		return base(route, 'POST', data, {'Content-Type': 'application/json'})
	},
	upload(filePath, formData = {}) {
		return new Promise((resolve, reject) => {
			let url = domain.upload + '/file/info/upload'
			wx.uploadFile({
				// 必需
				url,
				filePath,
				header: { token: domain.token },
				// 必需
				name: 'multipartFile',
				formData,
				success({ data }) {
					resolve(JSON.parse(data))
				},
				fail(err) {
					reject(err)
				},
			})
		})
  },
  
  uploadFile(route, data) {
    return base(route, 'POST', data, {'Content-Type': 'multipart/form-data'})
  }
}